import React, { Fragment } from 'react';
import { connect } from 'umi';
import { history } from 'umi';
import { Form, Input, Button, Row, Col, Table, Divider, Icon, Modal, Menu, Dropdown, message, Card } from 'antd';
import { get as getPath } from 'object-path';
import { formatMessage } from 'umi';
import LinkTo from '@/components/LinkTo';
import QueryPage from '@/components/QueryPage';

import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import authHelper from '@/utils/auth/helper';
import { withRoutePage } from '@/utils/enhanceUtils';
import routerReplace from '@/utils/routerReplace';
import Pagination from '@/components/Pagination';
import style from './NoticeDetail.less';

const { checkCode } = authHelper;

class NoticeManage extends React.Component {
    constructor(props) {
        super(props);
        const userInfo = JSON.parse(localStorage.getItem('user'));
        this.state = {
            userInfo,
            deleteModalVisible: false,
            deleteId: ''
        };
        this.authCode = new AuthCode(props.route.code).authCode;
    }

    componentDidMount() {
        const {
            location: { query },
            form
        } = this.props;
        form.setFieldsValue(query);

        this.fetchList();
    }

    componentWillUnmount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'noticeManage/save',
            payload: {
                pagination: {
                    current: 1,
                    pageSize: 10,
                    total: 0
                }
            }
        });
    }

    setModalVisible(deleteModalVisible) {
        this.setState({ deleteModalVisible });
    }

    fetchList = flag => {
        const { dispatch, noticeManage, form } = this.props;
        const { userInfo } = this.state;
        const { getFieldsValue } = form;
        const { pagination } = noticeManage;
        const searchData = getFieldsValue().searchName ? getFieldsValue().searchName.replace(/(^\s*)|(\s*$)/g, '') : '';
        const payload = {
            organizationCode: userInfo.firstOrgInfo.firstCompanyCode,
            userName: userInfo.userName,
            searchName: searchData,
            pageNo: flag ? 1 : pagination.current,
            pageSize: pagination.pageSize
        };
        dispatch({
            type: 'noticeManage/fetchList',
            payload,
            callback: res => {
                if (res.code !== 10000) {
                    message.error(res.msg);
                }
            }
        });
    };

    changeTable = async pagination => {
        const {
            dispatch,
            noticeManage: { pagination: curPagination }
        } = this.props;
        await dispatch({
            type: 'noticeManage/setPagination',
            pagination: {
                ...curPagination,
                ...pagination
            }
        });
        this.handleRouterReplace();
        this.fetchList();
    };

    deleteNotice = record => {
        this.setState({ deleteId: record.id }, () => {
            this.setState({ deleteModalVisible: true });
        });
    };

    createMenu = record => {
        const { route } = this.props;
        console.log('===============================================>sssss');
        const menu = (
            <Menu>
                {checkCode(this.authCode('edit')) && (
                    <Menu.Item key="0">
                        {/* <a
                            onClick={() =>
                                history.push(
                                    `${route.path}/noticeAdd?noticeId=${record.id}&action=edit`
                                )
                            }
                        >
                            {formatMessage({
                                id: 'columns.noticeList.action.edit'
                            })}
                        </a> */}
                        <LinkTo
                            to={`${route.path}/noticeAdd`}
                            query={{
                                noticeId: record.id,
                                action: 'edit'
                            }}
                        >
                            {formatMessage({
                                id: 'columns.noticeList.action.edit'
                            })}
                        </LinkTo>
                    </Menu.Item>
                )}
                {checkCode(this.authCode('delete')) && (
                    <Menu.Item key="1">
                        <a onClick={this.deleteNotice.bind(this, record)}>
                            {formatMessage({
                                id: 'columns.noticeList.action.delete'
                            })}
                        </a>
                    </Menu.Item>
                )}
            </Menu>
        );
        return menu;
    };

    handleRouterReplace() {
        const { noticeManage, form } = this.props;
        const { getFieldsValue } = form;
        const { pagination } = noticeManage;
        const searchData = getFieldsValue().searchName ? getFieldsValue().searchName.replace(/(^\s*)|(\s*$)/g, '') : '';
        const payload = {
            searchName: searchData,
            pageNo: 1,
            pageSize: pagination.pageSize
        };
        routerReplace({ query: payload });
    }

    sureDeleteNotice(deleteModalVisible) {
        const { dispatch } = this.props;
        dispatch({
            type: 'noticeManage/deleteNotice',
            payload: {
                noticeId: getPath(this.state, 'deleteId')
            },
            callback: res => {
                if (res.code === 10000) {
                    message.success(res.msg);
                    this.fetchList(true);
                } else {
                    message.error(res.msg);
                    this.fetchList(true);
                }
            }
        });
        this.setState({ deleteModalVisible });
    }

    render() {
        const { form } = this.props;
        const { loading, loadingDelete, noticeManage, route } = this.props;
        const { data, pagination } = noticeManage;
        const { getFieldDecorator } = form;
        // const showMOdule = [];
        // 处理menu的权限标识符
        // const getRouterAuthority = (result, pathname) => {
        //     if (result && result.length > 0) {
        //         result.map(item => {
        //             showMOdule.push(item.url);
        //             if (
        //                 item.children !== undefined &&
        //                 item.children !== null &&
        //                 item.children.length > 0
        //             ) {
        //                 getRouterAuthority(item.children, pathname);
        //             }
        //             return showMOdule;
        //         });
        //     }
        //     let showorno = false;
        //     showMOdule.forEach(item => {
        //         if (item === pathname) {
        //             showorno = true;
        //         }
        //     });
        //     if (showorno) {
        //         return true;
        //     }
        //     return false;
        // };
        const columns = [
            {
                title: formatMessage({ id: 'columns.noticeList.title' }),
                key: 'title',
                render: (text, record) => (
                    <div style={{ maxWidth: 300 }}>
                        <p
                            onClick={() => {
                                if (!checkCode(this.authCode('detail'))) return;
                                history.push({
                                    pathname: `${route.path}/noticeDetail`,
                                    query: { noticeId: record.id }
                                });
                            }}
                            style={{
                                cursor: 'pointer',
                                fontWeight: 'bold',
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis'
                            }}
                        >
                            {record.title}
                        </p>
                        <p
                            style={{
                                width: '100%',
                                height: '22px',
                                overflow: 'hidden',
                                textOverflow: '-o-ellipsis-lastline',
                                display: '-webkit-box',
                                WebkitLineClamp: '1',
                                flexDirection: 'column',
                                WebkitBoxOrient: 'vertical'
                            }}
                            className={style.noticeHtml}
                            // dangerouslySetInnerHTML={{
                            //     __html: xss(record.content)
                            // }}
                        >
                            {record.briefContent}
                        </p>

                        {/* /> */}
                    </div>
                )
            },
            {
                title: formatMessage({ id: 'columns.noticeList.startTime' }),
                dataIndex: 'startTime',
                key: 'startTime'
            },
            {
                title: formatMessage({ id: 'columns.noticeList.createUser' }),
                dataIndex: 'userName',
                key: 'userName'
            },
            {
                title: formatMessage({ id: 'columns.noticeList.recvOrganizationName' }),
                key: 'recvOrganizationName',
                width: 300,
                render: (text, record) => (
                    <div
                        style={{
                            width: '100%',
                            overflow: 'hidden',
                            textOverflow: '-o-ellipsis-lastline',
                            display: '-webkit-box',
                            WebkitLineClamp: '2',
                            flexDirection: 'column',
                            WebkitBoxOrient: 'vertical'
                        }}
                        title={record.recvOrganizationName}
                    >
                        {record.recvOrganizationName}
                    </div>
                )
            },
            {
                title: formatMessage({ id: 'columns.noticeList.action' }),
                key: 'action',
                fixed: 'right',
                width: 100,
                render: (text, record) => (
                    <span>
                        <AuthComponent code="office:personnel:progress:dimission:detail">
                            {/* <a
                                onClick={() =>
                                    history.push(
                                        `${route.path}/noticeDetail?noticeId=${record.id}`
                                    )
                                }
                            >
                                {formatMessage({
                                    id: 'columns.noticeList.action.detail'
                                })}
                            </a> */}

                            <LinkTo
                                to={`${route.path}/noticeDetail`}
                                query={{
                                    noticeId: record.id
                                }}
                            >
                                {formatMessage({
                                    id: 'columns.noticeList.action.detail'
                                })}
                            </LinkTo>
                            {record.flag && record.flag === '0' ? <Divider type="vertical" /> : null}
                        </AuthComponent>
                        {(checkCode(this.authCode('delete')) || checkCode(this.authCode('edit'))) && (
                            <div>
                                {record.flag && record.flag === '0' ? (
                                    <Dropdown overlay={() => this.createMenu(record)} trigger={['click']}>
                                        <a className="ant-dropdown-link" href="#">
                                            {formatMessage({
                                                id: 'columns.noticeList.action.more'
                                            })}{' '}
                                            <Icon type="down" />
                                        </a>
                                    </Dropdown>
                                ) : null}
                            </div>
                        )}
                    </span>
                )
            }
        ];

        return (
            <Fragment>
                <QueryPage
                    className={style.noticeQuery}
                    form={
                        <Form
                            layout="inline"
                            onSubmit={e => {
                                e.preventDefault();
                                this.handleRouterReplace();
                                this.fetchList(true);
                            }}
                        >
                            <Card
                                className={style.noticecard}
                                bordered={false}
                                title={
                                    <Row justify="space-between" type="flex">
                                        <Col>
                                            {formatMessage({
                                                id: 'menu.office.info.noticeManage'
                                            })}
                                        </Col>
                                        <Col>
                                            <AuthComponent code={this.authCode('add')}>
                                                <Form.Item>
                                                    <div
                                                        style={{
                                                            display: 'flex'
                                                        }}
                                                    >
                                                        <Button
                                                            type="primary"
                                                            onClick={() => history.push(`${route.path}/noticeAdd`)}
                                                        >
                                                            {formatMessage({
                                                                id: 'edit.model.addnotice.title'
                                                            })}
                                                        </Button>
                                                    </div>
                                                </Form.Item>
                                            </AuthComponent>
                                        </Col>
                                    </Row>
                                }
                            ></Card>
                            <Row span="24">
                                <Col
                                    style={{
                                        margin: '0 24px'
                                    }}
                                >
                                    <AuthComponent code={this.authCode('query')}>
                                        <Form.Item
                                        // label={formatMessage({
                                        //     id: 'edit.search.label'
                                        // })}
                                        >
                                            {getFieldDecorator('searchName')(
                                                <Input
                                                    placeholder={formatMessage({
                                                        id: 'edit.search.keyword'
                                                    })}
                                                    style={{ width: 248 }}
                                                    allowClear
                                                    // suffix={
                                                    //     <Icon
                                                    //         type="search"
                                                    //         style={{
                                                    //             color: 'rgba(0,0,0,0.15)'
                                                    //         }}
                                                    //     />
                                                    // }
                                                />
                                            )}
                                        </Form.Item>
                                        <Form.Item>
                                            <Button type="primary" htmlType="submit">
                                                {formatMessage({
                                                    id: 'edit.search.btn'
                                                })}
                                            </Button>
                                        </Form.Item>
                                    </AuthComponent>
                                    {/* <AuthComponent code={authCode('add')}>
                                        <Form.Item>
                                            <div style={{ display: 'flex' }}>
                                                <Button
                                                    style={{
                                                        position: 'relative',
                                                        verticalAlign: 'middle',
                                                        margin: '0 0 0 10px'
                                                    }}
                                                    onClick={() =>
                                                        history.push(
                                                            '/notice/article/mine/noticeAdd'
                                                        )
                                                    }
                                                >
                                                    {formatMessage({
                                                        id:
                                                            'edit.model.addnotice.title'
                                                    })}
                                                </Button>
                                            </div>
                                        </Form.Item>
                                    </AuthComponent> */}
                                </Col>
                            </Row>
                        </Form>
                    }
                    table={
                        <>
                            <Table
                                columns={columns}
                                dataSource={data}
                                rowKey="id"
                                onChange={this.changeTable}
                                style={{
                                    background: '#fff'
                                }}
                                scroll={{ x: 'max-content' }}
                                loading={loading}
                                pagination={false}
                            />
                            <Pagination {...pagination} onChange={this.changeTable} />
                        </>
                    }
                />
                <Modal
                    title={formatMessage({
                        id: 'edit.model.delate.title'
                    })}
                    confirmLoading={loadingDelete}
                    wrapClassName="vertical-center-modal"
                    visible={getPath(this.state, 'deleteModalVisible')}
                    onOk={() => this.sureDeleteNotice(false)}
                    onCancel={() => this.setModalVisible(false)}
                    centered
                >
                    <p>
                        {formatMessage({
                            id: 'edit.model.delate.message'
                        })}
                    </p>
                </Modal>
            </Fragment>
        );
    }
}
export default withRoutePage(
    connect(({ noticeManage, loading }) => ({
        noticeManage,
        loading: loading.models.noticeManage,
        loadingDelete: loading.effects['noticeManage/fetchDelete']
    }))(Form.create()(NoticeManage))
);
